import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LoginResponse } from '@/api/driver/login'

// 用户信息接口
interface UserInfo {
  id: number
  name: string
  phone: string
  avatar?: string
  vehicleNo?: string
  status: number
}

// 认证状态接口
interface AuthState {
  token: string | null
  userInfo: UserInfo | null
  isAuthenticated: boolean
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('driver_token'))
  const userInfo = ref<UserInfo | null>(null)
  const isAuthenticated = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('driver_token', newToken)
  }

  // 清除token
  const clearToken = () => {
    token.value = null
    localStorage.removeItem('driver_token')
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    localStorage.setItem('driver_user_info', JSON.stringify(info))
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    localStorage.removeItem('driver_user_info')
  }

  // 从本地存储加载用户信息
  const loadUserInfo = () => {
    const stored = localStorage.getItem('driver_user_info')
    if (stored) {
      userInfo.value = JSON.parse(stored)
    }
  }

  // 登出
  const logout = () => {
    clearToken()
    clearUserInfo()
  }

  // 初始化
  const initAuth = () => {
    loadUserInfo()
  }

  return {
    // 状态
    token,
    userInfo,
    isAuthenticated,
    
    // 方法
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    loadUserInfo,
    logout,
    initAuth
  }
})